'use strict';

const Service = require('egg').Service;

class PraiseService extends Service {
    async setStatus(params) {
        const { model } = this.app
        const { type, target, targetId, userId } = params

        let sql = {
            where: {
                user_id: userId,
                target,
                target_id: targetId,
            },
            defaults: {
                user_id: userId,
                type,
                target,
                target_id: targetId,
                create_time: (new Date).getTime() / 1000,
                update_time: (new Date).getTime() / 1000
            }
        }

        let result = await model.Praise.findOrCreate(sql)

        // 已存在
        if (!result[1]) {
            let updateSql = {
                type,
                status: 1
            }
            // 点赞或点踩有效时，点一次不同的操作
            if (type != result[0].type && result[0].status == 1) throw { code: '02', msg: '已经点赞或者点踩过' }

            // 点赞或点踩有效时，再点一次相同的操作 取消
            if (type == result[0].type && result[0].status == 1) updateSql.status = 2
            
            result = await model.Praise.update(updateSql, {
                where: {
                    user_id: userId,
                    target,
                    target_id: targetId,
                }
            });
            if (result.length < 1) throw { code: '02', msg: '修改失败' }
            // console.log(result);
            result = {
                type,
                status: updateSql.status
            }
        } else {
            result = {
                type,
                status: 1
            }
        }

        return result
    }
}

module.exports = PraiseService;
